package com.healthcloud.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.healthcloud.dao.SmartDAOmapper;
import com.healthcloud.entity.*;
import com.healthcloud.utils.RRException;
import com.healthcloud.vo.Msgdata;
import com.healthcloud.vo.QuadataVO;
import com.healthcloud.vo.TestdataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 服务类
 * @Author yucl
 * @date 2018/7/24
 */
@Service
@Transactional
@Slf4j
public class SmartService {


    @Autowired
    private SmartDAOmapper smartDAO;

//    @Autowired
//    private Producer producer;


    public void insertTestData(TestdataVO testdataVO) {


        TestDataModel model = new TestDataModel();

        String ti = "";
        if(!StringUtils.isEmpty(testdataVO.getResultTime())){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMdd");
            try {
                Date d = format.parse(testdataVO.getResultTime());
                ti = format2.format(d);
            } catch (ParseException e) {
                throw new RRException("测试时间格式不正确",e);
            }
        }
        //目前的规则 年月日+身份证(18位)+仪器ID update by lixiaoxiao 20160921
        String testListId = ti+ testdataVO.getPatientIdCard()+testdataVO.getMechineId();
        model.setIDCard(testdataVO.getPatientIdCard());//
        model.setTestValue(testdataVO.getTestResult());//暂时放testresult
        model.setMKMedicalinstrumentId(testdataVO.getMechineId());
        model.setTestItemNameen(testdataVO.getTestProject());
        model.setTestResult(testdataVO.getTestResult());
        model.setTestCh(testdataVO.getTestCh());
        model.setValueUnit(testdataVO.getResultUnit());
        model.setTestTime(testdataVO.getResultTime());
        model.setTestWarming(testdataVO.getResultWarming());
        model.setProjectBatch(testdataVO.getProjectBatch());
        model.setPatientIdCard(testdataVO.getPatientIdCard());
        model.setPatientPhone(testdataVO.getPatientPhone());
        model.setPatientName(testdataVO.getPatientName());
        model.setClinicalDept(testdataVO.getClinicalDept());
        model.setCliniainsName(testdataVO.getCliniainsName());
        model.setSamplingTime(testdataVO.getSamplingTime());
        model.setInspectionDept(testdataVO.getInspectionDept());
        model.setInspectorName(testdataVO.getInspectorName());
        model.setSampleNo(testdataVO.getSampleNo());
        model.setConsultHigh(testdataVO.getConsultHigh());
        model.setConsultLow(testdataVO.getConsultLow());
        model.setTestListId(testListId);
        if(StringUtils.isEmpty(testdataVO.getDataType())){
            model.setDataType("1");
        }else{
            model.setDataType(testdataVO.getDataType());
        }
        model.setMealType(testdataVO.getMealType());
        model.setConsultResult(testdataVO.getConsultResult());
        model.setResultLow(testdataVO.getResultLow());
        model.setResultHigh(testdataVO.getResultHigh());
        model.setPatientAddress(testdataVO.getPatientAddress());
        model.setPatientImage(testdataVO.getPatientImage());


        //验证数据唯一性 项  项目+设备号+测试时间+身份证+通道
        List<TestResultModel> tr = smartDAO.onlyCheckTestResult(model);
        if(tr.size() >= 1){
            throw new RRException("数据已经存在");
        };

        ProjectKindModel pm = new ProjectKindModel();
        pm.setTestItemNameEn(testdataVO.getTestProject());
        ProjectKindModel pkModel = smartDAO.searchProjKind(pm);
        if(pkModel != null){
            model.setTestItemCode(pkModel.getTestItemCode());
            model.setTestItemName(pkModel.getTestItemName());
            model.setTestKindCode(pkModel.getTestKindCode());
            model.setTestKindName(pkModel.getTestKindName());
            model.setTestKindNameen(pkModel.getTestKindNameEn());
        }else{
            throw new RRException("TestProject的值不不正确");
        }
        try{
            smartDAO.insertTestData(model);

        }catch(Exception e){
            throw new RRException("未知错误：",e);

        }


    }


    public void insertQuaData(QuadataVO quadataVO) throws Exception{

        QualityModel model = new QualityModel();
        model.setMachineId(quadataVO.getMechineId());
        model.setQuaResult(quadataVO.getQuaResult());
        model.setQuanName(quadataVO.getQuanName());
        model.setProjectBatch(quadataVO.getProjectBatch());
        model.setQuaCh(quadataVO.getQuaCh());
        model.setQuaDateTime(quadataVO.getQuaDateTime());
        model.setQuaBatch(quadataVO.getQuaBatch());
        model.setQuaHL(quadataVO.getQuaHL());
        model.setQuaValue(quadataVO.getQuaValue());
        model.setQuaSD(quadataVO.getQuaSD());

        smartDAO.insertQuaData(model);

    }



    public void insertLogData(com.healthcloud.vo.LogdataVO logdataVO) throws Exception{
        LogModel model = new LogModel();

        model.setMachineId(logdataVO.getMechineId());
        model.setLogCode(logdataVO.getLogCode());
        model.setLogType(logdataVO.getLogType());
        model.setLogInfo(logdataVO.getLoginfo());
        smartDAO.insertLogData(model);

    }


    public List<VersionModel> searchVersion(String appliance, String bVersion, String childVersion) {
        VersionModel model = new VersionModel();
        model.setAppCode(appliance);
        model.setChildVersion(childVersion);
        model.setVersion(bVersion);
        return smartDAO.searchVersion(model);
    }


    public String searchCheck(String machineId,String ch,String projectBatch,String projectName) {
        CheckKBModel model = new CheckKBModel();
        model.setMachineId(machineId);
        model.setCh(ch);
        model.setProjectBatch(projectBatch);
        model.setProjectName(projectName);
        CheckKBModel result = smartDAO.searchCheck(model);
        if(result != null){
            result.setCheckStatus("1");
            smartDAO.saveCheck(result);
            return result.getKValue()+","+result.getBValue();
        }
        return "";
    }


//    public List<TestDataModel> searchTestData() {
//        return smartDAO.searchTestData();
//    }




    public List<TestResultModel> getTestResults(String idCard, String beginTime,
                                                String endTime, String pagesize, String pageindex,
                                                String testItemName) throws Exception {
        return  getTestResults(idCard,beginTime,endTime,pagesize,pageindex,testItemName,null);
    }


    public List<TestResultModel> getTestResults( String idCard, String beginTime,
                                                 String endTime, String pagesize, String pageindex,
                                                 String testItemName, String companycode) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
        Date endTimeDate = formatter1.parse(endTime);
        Date beginTimeDate = formatter1.parse(beginTime);
        String endTimeStr=formatter.format(endTimeDate);
        String beginTimeStr=formatter.format(beginTimeDate);
        return smartDAO.getTestResults(idCard, beginTimeStr, endTimeStr, pagesize, pageindex, testItemName,companycode);
    }


    public List<TestResultModel> checkTestResult(String testListId) {
        return smartDAO.checkTestResult(testListId,null);
    }




    public List<SNCheckModel> checkSN(SNCheckModel model) {
        return smartDAO.checkSN(model);
    }


    public List<UserModel> searchUserList(String hospId) {
        return smartDAO.searchUserList(hospId);
    }


    public List<BpModel> searchBpList(String idCard, String beginTime,
                                      String endTime, String pagesize, String pageindex) throws Exception{
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
        Date endTimeDate = formatter1.parse(endTime);
        Date beginTimeDate = formatter1.parse(beginTime);
        String endTimeStr=formatter.format(endTimeDate);
        String beginTimeStr=formatter.format(beginTimeDate);
        return smartDAO.searchBpList(idCard, beginTimeStr, endTimeStr, pagesize, pageindex);
    }


    public List<BsModel> searchBsList(String idCard, String beginTime,
                                      String endTime, String pagesize, String pageindex) throws Exception{
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
        Date endTimeDate = formatter1.parse(endTime);
        Date beginTimeDate = formatter1.parse(beginTime);
        String endTimeStr=formatter.format(endTimeDate);
        String beginTimeStr=formatter.format(beginTimeDate);
        return smartDAO.searchBsList(idCard, beginTimeStr, endTimeStr, pagesize, pageindex);
    }


    public void bsUpload(Msgdata msgdata) throws Exception{

        BsUploadModel model = new BsUploadModel();
        model.setDevicesn(msgdata.getDevicesn());
        model.setUsercode(msgdata.getUsercode());
        model.setOpenid(msgdata.getOpenid());
        model.setResult(msgdata.getResult());
        model.setUnit(msgdata.getUnit());
        model.setTesttime(msgdata.getTesttime());
        model.setFoodstatus(msgdata.getFoodstatus());
        model.setIdCard(msgdata.getIdCard());
        smartDAO.bsUpload(model);
    }


    public int bpUpload(BpUploadModel model) {
        return smartDAO.bpUpload(model);
    }

    public List<BpUploadModel> selectOne(BpUploadModel model){
        return smartDAO.selectOne(model.getImei(),model.getSys(),model.getDia(), model.getPul(),model.getTime());
    }

    /**
     * 执行异步任务
     * 血压测试结果上传
     */
    @Async("asyncServiceExecutor")
    public void bpExecuteAsync(BpUploadModel bpUploadModel) {

        try {
            //睡眠2秒
            Thread.sleep(1000 * 2);

            List<BpUploadModel> bpUploadModels = smartDAO.selectOne(bpUploadModel.getImei(), bpUploadModel.getSys(), bpUploadModel.getDia(), bpUploadModel.getPul(), bpUploadModel.getTime());
            if (bpUploadModels !=null && bpUploadModels.size()>0){
                TestDataModel entity = new TestDataModel();
                entity.setMKMedicalinstrumentId(bpUploadModel.getImei());
                entity.setTestTime(String.valueOf(bpUploadModels.get(0).getCreateTime()));
                List<SaveMeasureModel> list = smartDAO.getSaveMeasureVO(entity);
                if (list != null && list.size() > 0){
                    for (SaveMeasureModel model : list){
                        String jsonString = JSON.toJSONStringWithDateFormat(model,"yyyy-MM-dd HH:mm:ss");
                        String result = HttpUtil.post("http://iot.dongkangmedical.com/gateway/medicine/api/blood/saveMeasure", jsonString);

                        SmartUploadResult smartUploadResult = new SmartUploadResult();
                        smartUploadResult.setImei(entity.getMKMedicalinstrumentId());
                        smartUploadResult.setUploadTime(entity.getTestTime());
                        smartUploadResult.setUploadParam(jsonString);
                        smartUploadResult.setReturnResult(result);
                        smartDAO.insertSmartUploadResult(smartUploadResult);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 执行异步任务
     * 血糖测试结果上传
     */
    @Async("asyncServiceExecutor")
    public void bsExecuteAsync(Msgdata msgdata) {

        try {
            Thread.sleep(1000 * 2);

            TestDataModel entity = new TestDataModel();
            entity.setMKMedicalinstrumentId(msgdata.getDevicesn());
            entity.setTestTime(String.valueOf(msgdata.getTesttime()));
            List<SaveMeasureModel> list = smartDAO.getSaveMeasureVO(entity);
            if (list != null && list.size() > 0){
                for (SaveMeasureModel model : list){
                    String jsonString = JSON.toJSONStringWithDateFormat(model,"yyyy-MM-dd HH:mm:ss");
                    String result = HttpUtil.post("http://iot.dongkangmedical.com/gateway/medicine/api/blood/saveMeasure", jsonString);

                    SmartUploadResult smartUploadResult = new SmartUploadResult();
                    smartUploadResult.setImei(entity.getMKMedicalinstrumentId());
                    smartUploadResult.setUploadTime(entity.getTestTime());
                    smartUploadResult.setUploadParam(jsonString);
                    smartUploadResult.setReturnResult(result);
                    smartDAO.insertSmartUploadResult(smartUploadResult);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws Exception{
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//        String dateTime = sdf.format(new Date());
//        Random random = new Random();
//        int _random = random.nextInt(100);
//        String sign = EncryptUtil.encryption(10*_random + "15988614940");
//        String smsUrl = "http://192.168.20.61/Restful/sms/set?sid=1&tophone="+"15988614940"+"&smscontent=推送成功："+"gson.toJson(model)"+"&smstype=1&timestamp="+dateTime+"&modelid=26937"+"&random="+_random+"&sign="+sign;
//
//
//        HttpClient httpclient = new DefaultHttpClient();
//        HttpGet httpGet = new HttpGet(smsUrl);
//        httpGet.addHeader("Content-type", "application/x-www-form-urlencoded");
//        HttpResponse response = httpclient.execute(httpGet);
//    }


}
